#!/usr/bin/env bash
set -uo pipefail

#==============================================================#
# File      :   pg-create-extension
# Ctime     :   2020-12-16
# Mtime     :   2020-12-17
# Desc      :   create extension in target database and target schema
# Path      :   /pg/bin/pg-create-extension
# Depend    :   psql
# Author    :   Vonng(fengruohang@outlook.com)
# Copyright (C) 2018-2021 Ruohang Feng
#==============================================================#

PROG_NAME="$(basename $0))"
PROG_DIR="$(cd $(dirname $0) && pwd)"


#==============================================================#
#                             Usage                            #
#==============================================================#
function usage() {
	cat <<-'EOF'
		NAME
			pg-create-extension   -- create extension in target database and target schema

		SYNOPSIS
			pg-create-extension <database> <schema> <extensions>

		DESCRIPTION
			pg-create-extension will create extension(s) in target database within target schema
			extensions are comma separated list of extension names

		EXAMPLES
			Install monitor extensions into schema monitor and some default extensions into
			schema public:

			pg-create-extension template1 monitor pg_stat_statements,pgstattuple,pg_qualstats,pg_buffercache,pageinspect,pg_prewarm,pg_visibility,pg_freespacemap,pg_repack
			pg-create-extension template1 public  tablefunc,postgres_fdw,file_fdw,btree_gist,btree_gin,pg_trgm
			pg-create-extension template1 public  postgis


	EOF
	exit 1
}



#--------------------------------------------------------------#
# Name: pg-create-extension
# Desc: create extension in target database and target schema
# Arg1: database name, template1 by default
# Arg2: schema name, public by default
# Arg3: extension name, list of extension name
#--------------------------------------------------------------#
function pg-create-extension(){
	local database=${1-'template1'}
	local schema=${2-'public'}
	shift
	shift
	if (( $# == 0 )); then
		echo "at least one extension is needed"
		return 1
	fi

	echo "CREATE EXTENSION $@ WITH ${schema} ON DATABASE ${database};"
	for extension_name in "$@"
	do
		psql -qAXtw "${database}" <<-EOF
			CREATE EXTENSION IF NOT EXISTS "${extension_name}" WITH SCHEMA "${schema}";
		EOF
	done
}


#==============================================================#
#                             Main                             #
#==============================================================#

if (( $# <= 1 )); then
	usage
fi
case "$1" in
	-h | --help) usage ;;
esac

pg-create-extension "$@"